package com.syq.play.util;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.List;

import com.syq.play.adapter.FolderAdapter;
import com.syq.play.db.entity.SongManager;
import com.syq.play.model.FolderModel;


import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.GridView;
import android.widget.ListView;
/**
 * Bitmap帮助类
 * @author ShiYiqiong
 *
 */
public class BitmapUtil {
	private static String TAG="BitmapUtil";
	private  MyThread mThread;
	private GridView gridView;
	private FolderAdapter myAdapter;
	private String selection;
	 private Handler mHandler=new Handler(){
	    	@Override
	    	public void handleMessage(Message msg) {
	    		super.handleMessage(msg);
	    		myAdapter.notifyDataSetChanged();
	    	}
	    };
	/**
	 * 异步获取mp3封面
	 * @param GridView
	 * @param myAdapter 需要更新图片的适配器
	 */
    public  synchronized  void updateAdapterBitmap(final GridView gridView, final FolderAdapter myAdapter, final String selection){
    	this.gridView=gridView;
		this.myAdapter=myAdapter;
		this.selection=selection;
    	if(myAdapter!=null){
    		if(mThread==null){
	    		mThread=new MyThread();
	    		mThread.start();
    		}else{
    			if(!mThread.isRun){
    				mThread=new MyThread();
    				mThread.start();
    			}
    			
    		}	
    	}
    }
     class  MyThread extends Thread{
    	public boolean isRun=false;
    	public MyThread(){
    		super();
    	}
    	
    	@Override
    	public void run() {
    		super.run();
    		isRun=true;
    		List<FolderModel> listData=myAdapter.getListData();
			for(;;){
				if(gridView.getLastVisiblePosition()>-1){
					break;
				}
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			for(int i=gridView.getFirstVisiblePosition(), size=gridView.getLastVisiblePosition(); i<=size; i++){
				if(listData.size()>i){
					if(listData.get(i).getFolderName()!=null){
						if(listData.get(i).getIcon()==null){
							Bitmap bitmap=SongManager.getInstance().getSongIcon(selection,listData.get(i).getFolderName());
							listData.get(i).setIcon(bitmap);
							mHandler.sendMessage(new Message());
						}
					}
				}
			}
			isRun=false;
    	}
    }
    
}
